package com.enzoism.springboot.dive.a2Interrupt;

import lombok.SneakyThrows;
import lombok.extern.java.Log;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
import java.nio.charset.StandardCharsets;

public class PipInterruptExample {

    private static Logger logger = LogManager.getLogger(PipInterruptExample.class);

    //    @SneakyThrows
    public static void main(String[] args) {
        try {
            // 1-创建一个管道
            Pipe pipe = Pipe.open();

            // 2-从管道读取数据
            Thread readThread = new Thread(() -> {
                try {
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    while (true) {
                        int bytesRead = pipe.source().read(buffer);
                        if (bytesRead == -1) {
                            break;
                        }
                        buffer.flip();
                        byte[] bytes = new byte[buffer.limit()];
                        buffer.get(bytes);
                        logger.info("Read：{}", new String(bytes));
                        buffer.clear();
                    }
                } catch (Exception e) {
                    logger.error("-------readThread异常", e);
                }
            });

            // 3-从管道写入数据
            Thread writeThread = new Thread(() -> {
                try {
                    while (true) {
                        String str = "Hello World！";
                        byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
                        ByteBuffer buffer = ByteBuffer.wrap(bytes);
                        pipe.sink().write(buffer);
                        logger.info("Written：{}", str);
                    }
                } catch (Exception e) {
                    logger.error("-------writeThread异常", e);
                }
            });

            // 4-启动线程
            readThread.start();
            writeThread.start();

            // 5-中断线程
            readThread.interrupt();

            // 6-等待线程执行
            readThread.join();
            writeThread.join();

            // 7-关闭通道
            pipe.source().close();
            ;
            pipe.sink().close();
        } catch (IOException e) {
            logger.error("-------IOException异常", e);
        } catch (InterruptedException e) {
            logger.error("-------InterruptedException异常", e);
        }
    }
}
